/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ws.service;

import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.ResourceContext;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import entidade.persistencia.AreaAtuacao;
import entidade.persistencia.Empresa;
import entidade.persistencia.Usuario;
import java.util.List;
import ws.converter.EmpresaConverter;
import java.util.List;
/**
 *
 * @author victorinox
 */

public class EmpresaResource {
    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;
    protected Integer id;
  
    /** Creates a new instance of EmpresaResource */
    public EmpresaResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * Get method for retrieving an instance of Empresa identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of EmpresaConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public EmpresaConverter get(@QueryParam("expandLevel")
    @DefaultValue("1")
    int expandLevel) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            return new EmpresaConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
        } finally {
            PersistenceService.getInstance().close();
        }
    }

    /**
     * Put method for updating an instance of Empresa identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an EmpresaConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(EmpresaConverter data) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            EntityManager em = persistenceSvc.getEntityManager();
            updateEntity(getEntity(), data.resolveEntity(em));
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Delete method for deleting an instance of Empresa identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            deleteEntity(getEntity());
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Returns an instance of Empresa identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of Empresa
     */
    protected Empresa getEntity() {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        try {
            return (Empresa) em.createQuery("SELECT e FROM Empresa e where e.empresaId = :empresaId").setParameter("empresaId", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    protected Empresa updateEntity(Empresa entity, Empresa newEntity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        List<Usuario> usuarioCollection = entity.getUsuarioCollection();
        List<Usuario> usuarioCollectionNew = newEntity.getUsuarioCollection();
        AreaAtuacao areaAtuacaoId = entity.getAreaAtuacaoId();
        AreaAtuacao areaAtuacaoIdNew = newEntity.getAreaAtuacaoId();
        List<Empresa> empresaCollection = entity.getEmpresaCollection();
        List<Empresa> empresaCollectionNew = newEntity.getEmpresaCollection();
        Empresa matrizId = entity.getMatrizId();
        Empresa matrizIdNew = newEntity.getMatrizId();
        entity = em.merge(newEntity);
        for (Usuario value : usuarioCollection) {
            if (!usuarioCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from usuarioCollection"));
            }
        }
        for (Usuario value : usuarioCollectionNew) {
            if (!usuarioCollection.contains(value)) {
                Empresa oldEntity = value.getEmpresaId();
                value.setEmpresaId(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getUsuarioCollection().remove(value);
                }
            }
        }
        if (areaAtuacaoId != null && !areaAtuacaoId.equals(areaAtuacaoIdNew)) {
            areaAtuacaoId.getEmpresaCollection().remove(entity);
        }
        if (areaAtuacaoIdNew != null && !areaAtuacaoIdNew.equals(areaAtuacaoId)) {
            areaAtuacaoIdNew.getEmpresaCollection().add(entity);
        }
        for (Empresa value : empresaCollection) {
            if (!empresaCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from empresaCollection"));
            }
        }/*
        for (Empresa value : empresaCollectionNew) {
            if (!empresaCollection.contains(value)) {
                Empresa oldEntity = value.getEmpresaCollection();
                value.setEmpresaCollection(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getEmpresaCollection().remove(value);
                }
            }
        }*/
        if (matrizId != null && !matrizId.equals(matrizIdNew)) {
            matrizId.getEmpresaCollection().remove(entity);
        }
        if (matrizIdNew != null && !matrizIdNew.equals(matrizId)) {
            matrizIdNew.getEmpresaCollection().add(entity);
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    protected void deleteEntity(Empresa entity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        if (!entity.getUsuarioCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because usuarioCollection is not empty."));
        }
        AreaAtuacao areaAtuacaoId = entity.getAreaAtuacaoId();
        if (areaAtuacaoId != null) {
            areaAtuacaoId.getEmpresaCollection().remove(entity);
        }
        if (!entity.getEmpresaCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because empresaCollection is not empty."));
        }
        Empresa matrizId = entity.getMatrizId();
        if (matrizId != null) {
            matrizId.getEmpresaCollection().remove(entity);
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of UsuarioesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of UsuarioesResource
     */
    @Path("usuarioCollection/")
    public UsuarioesResource getUsuarioCollectionResource() {
        UsuarioCollectionResourceSub resource = resourceContext.getResource(UsuarioCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of AreaAtuacaoResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of AreaAtuacaoResource
     */
    @Path("areaAtuacaoId/")
    public AreaAtuacaoResource getAreaAtuacaoIdResource() {
        AreaAtuacaoIdResourceSub resource = resourceContext.getResource(AreaAtuacaoIdResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of EmpresasResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of EmpresasResource
     */
    @Path("empresaCollection/")
    public EmpresasResource getEmpresaCollectionResource() {
        EmpresaCollectionResourceSub resource = resourceContext.getResource(EmpresaCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of EmpresaResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of EmpresaResource
     */
    @Path("matrizId/")
    public EmpresaResource getMatrizIdResource() {
        MatrizIdResourceSub resource = resourceContext.getResource(MatrizIdResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    public static class UsuarioCollectionResourceSub extends UsuarioesResource {

        private Empresa parent;

        public void setParent(Empresa parent) {
            this.parent = parent;
        }

        @Override
        protected List<Usuario> getEntities(int start, int max, String query) {
            List<Usuario> result = new java.util.ArrayList<Usuario>();
            int index = 0;
            for (Usuario e : parent.getUsuarioCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class AreaAtuacaoIdResourceSub extends AreaAtuacaoResource {

        private Empresa parent;

        public void setParent(Empresa parent) {
            this.parent = parent;
        }

        @Override
        protected AreaAtuacao getEntity() {
            AreaAtuacao entity = parent.getAreaAtuacaoId();
            if (entity == null) {
                throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
            }
            return entity;
        }
    }

    public static class EmpresaCollectionResourceSub extends EmpresasResource {

        private Empresa parent;

        public void setParent(Empresa parent) {
            this.parent = parent;
        }

        @Override
        protected List<Empresa> getEntities(int start, int max, String query) {
            List<Empresa> result = new java.util.ArrayList<Empresa>();
            int index = 0;
            for (Empresa e : parent.getEmpresaCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class MatrizIdResourceSub extends EmpresaResource {

        private Empresa parent;

        public void setParent(Empresa parent) {
            this.parent = parent;
        }

        @Override
        protected Empresa getEntity() {
            Empresa entity = parent.getMatrizId();
            if (entity == null) {
                throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
            }
            return entity;
        }
    }
}
